import React, {useMemo} from 'react';
import DocumentTitle from 'react-document-title';
import queryString from 'query-string';

/**
 * 路由组件包装组件，用于增加目标组件的属性
 */
const RouteWrapper = (props: any) => {
    let {component: Component, route, ...restProps} = props;

    // useMemo 缓存query，避免每次生成生的query
    const queryMemo = useMemo(() => {
        const queryReg = /\?\S*/g;
        const matchQuery = (reg: RegExp) => {
            const queryParams = restProps.location.search.match(reg);
            return queryParams ? queryParams[0] : '{}';
        };
        return queryString.parse(matchQuery(queryReg));
    }, [restProps.location.search]);

    // 合并查询参数到 props
    const mergeQueryToProps = () => {
        const queryReg = /\?\S*/g;
        // 在路由器中删除查询参数
        const removeQueryInRouter = (restProps: any, reg: RegExp) => {
            const {params} = restProps.match;
            Object.keys(params).forEach((key) => {
                params[key] = params[key] && params[key].replace(reg, '');
            });
            restProps.match.params = {...params};
        };

        removeQueryInRouter(restProps, queryReg);

        return {
            ...restProps,
            query: queryMemo,
        };
    };

    return (
        <DocumentTitle title={route.title}>
            <Component {...mergeQueryToProps()} />
        </DocumentTitle>
    );
};

export default RouteWrapper;
